var basePath= $('#basePath').val();
var shopId =$('#shopId').val();
$(function(){
    var jcrop_api;//jcrop 对象
    var imgWidth;//图片原始大小
    var itemId= $("#itemId").val();
    var itemOrgId= $("#itemOrgId").val();
    var isEdit= $("#edit").val();
    //确认裁剪
    $("#imgCrop .complete").click(function(e){
        e.preventDefault();
        $("#needCut").val("true");//设置需要裁减
        $(".main").show();
        $("#imgCrop").hide();
        jcrop_api.destroy();
        $("#originalImg").replaceWith(' <img id="originalImg" style="min-width:300px;max-width:600px;width:90%"/>');
        imageUpload("imageFile");
    });

    //取消裁剪
    $("#imgCrop .cancel").click(function(e){
        e.preventDefault();
        $("needCut").val("false");
        $("#cutX").val("");
        $("#cutY").val("");
        $("#destWidth").val("");
        $("#destHeight").val("");
        $(".main").show();
        $("#imgCrop").hide();
        jcrop_api.destroy();
        $("#originalImg").replaceWith(' <img id="originalImg" style="min-width:300px;max-width:600px;width:90%"/>');
        $("body").attr("style","margin-top:0px;");
    });

    /*//图片选择事件
    $(document).on("change","#imageFile",function(){
        console.log("imageFile changed");
        if(document.getElementById("imageFile").files.length==0){
            return;
        }
		//直接上传图片
        $("#needCut").val("false"); 
        imageUpload($("imageFile"));
    });*/
});

function addPictureP(obj){//点击添加图片
	var keyp = $(obj).attr("key");
	if(keyp == "1"){
		//console.log("addPictureP");
		var imageFileId = $(obj).attr("imageFile");
		$("#"+imageFileId).click();
		$(obj).attr("key","0");
	}
}

function imageFileChange(obj){
	//console.log("imageFile changed");
	var index = $(obj).attr("index");
	var imageFileId = $(obj).attr("id");
        if(document.getElementById(imageFileId).files.length==0){
			$("[imagefile='"+imageFileId+"']").attr("key","1");
            return;
        }
		//直接上传图片
        $("#needCut").val("false"); 
        imageUpload($("imageFile"),index);
}

// 文件上传
    function imageUpload(elementId,index){
        var data={
            //categoryId:$("#categoryId").val(),
            //fileCategory:$("#fileCategory").val(),
            fileCategory:2,
            shopId:shopId,
            //needCut:$("#needCut").val(),
            
        }
        if(data.needCut){
            data.cutX=$("#cutX").val();
            data.cutY=$("#cutY").val();
            data.destWidth=$("#destWidth").val();
            data.destHeight=$("#destHeight").val();
        }
        $.ajaxFileUpload({
            "url": basePath + "/shopE/fileUpload!fileUpload.action", // 4.5.2	单文件上传
            "secureuri": false,
            "fileElementId": "imageFile_"+index,
            "dataType": "json",
            "data": data,
            "success": function(result) {
                var color = "red";
                if(result.flag) {
					var liStr = '<li><img src="'+result.valuePath+'" /><i class="delect" index="'+index+'" onclick="delectThisPic(this);"></i></li>'
					$(".pic_list_"+index).append(liStr);
					$("#add_picture_"+index).attr("key","1");
					var height1 = $(".pic_list_"+index).find("li").last().height();
					var width1 = $(".pic_list_"+index).find("li").last().width();
					var image = new Image();
						image.src = result.valuePath;
						image.onload = function(){
							if(image.height>height1 && image.width>width1){
								if(image.height<image.width){
									var heiLi = height1/image.height;
									$(".pic_list_"+index).find("li").last().find("img").attr("style","height:"+height1+";position:absolute;left:-"+(image.width*heiLi-width1)/2+";");
								}else if(image.height>image.width){
									var widLi = width1/image.width;
									$(".pic_list_"+index).find("li").last().find("img").attr("style","width:"+width1+";position:absolute;left:0;top:-"+(image.height*widLi-height1)/2+";");
								}else{
									$(".pic_list_"+index).find("li").last().find("img").attr("style","width:100%");
								}
							}
						}
					var checkAdnews = $(".pic_list_"+index).attr("adnews");//是否发布头条上传
					if(checkAdnews == "true"){
						checkAdnewsTypeId();//发布头条上传封面图片限制
					}else{
						var len = $(".pic_list_"+index).find("li").length;
					    if(len == 5){//超过5张图片隐藏上传按钮
						    $("#add_picture_"+index).hide();
					    }
					}		
                    //$("body").attr("style","margin-top:0px;");
                    color="green";
					new $.tip({
						"width": "200px",
						"content": "上传成功",
						"time": 500,
						"color": color
					}).run();
                }else{
					new $.tip({
						"width": "200px",
						"content": "上传失败",
						"time": 500,
						"color": color
					}).run();
				}
            },
            "complete": function() {

            }
        });
    }
	
	function checkAdnewsTypeId(){
		var len = $(".pic_list_0").find("li").length;
		var AdTypeId = $("#ad_cover").attr("typeId");
		if(AdTypeId == "adNews_1_1" || AdTypeId == "adNews_1_2"){//一图
			if(len == 1){
				$("#add_picture_0").hide();
			}
		}else if(AdTypeId == "adNews_2" && len == 2){//二图
			$("#add_picture_0").hide();
		}else if(AdTypeId == "adNews_3" && len == 3){//三图
			$("#add_picture_0").hide();
		}else if(AdTypeId == "adNews_4" && len == 4){//四图
			$("#add_picture_0").hide();
		}
	}

    /*图片预览和设置裁剪*/
    function imagePreview(elementId){
        var iMaxFilesize = 1048576; // 1MB
        var oFile = document.getElementById(elementId).files[0];
        console.log(oFile.name);//读取文件名
        // filter for image files
        var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/jpg|image\/png|image\/tiff)$/i;
        if (! rFilter.test(oFile.type)) {
            alert("图片格式不正确");

            return;
        }

        // little test for filesize
        if (oFile.size > iMaxFilesize) {
            alert("图片大小超过1M");

            return;
        }

        // prepare HTML5 FileReader
        var oReader = new FileReader();
        // read selected file as DataURL
        oReader.readAsDataURL(oFile);
        oReader.onloadend = function(e){

            // e.target.result contains the DataURL which we will use as a source of the image
            $("#originalImg").attr("src",e.target.result);
            $("#croppedImg").attr("src",e.target.result);
            var img = new Image();
            img.src =e.target.result ;
            imgWidth = img.width; //图片实际宽度

            if(jcrop_api!=null){
                jcrop_api.setImage(e.target.result,function() {
                    /* var bounds = jcrop_api.getBounds();
                     var boundx = bounds[0];
                     var boundy = bounds[1];
                     jcrop_api.setSelect([0, 0, 320, 320]);//设置选择框*/
                });


            }
            JCropwithPreview($("#originalImg"),$(".preview-pane"),$(".preview-container"),$("#croppedImg"));


        };
    }

    /*图片裁剪*/
    function JCropwithPreview(target,$preview_pane,$preview_container,$preview_img) {
        if (jcrop_api != null)
            jcrop_api.destroy();

        target.Jcrop({
            allowSelect: false,
            allowResize: true,
            touchSupport: true,
            onChange: updatePreview,
            onSelect: updatePreview,
            aspectRatio: 1

        }, function () {
            jcrop_api = this;

            var bounds = jcrop_api.getBounds();
            var boundx = bounds[0];
            var boundy = bounds[1];
            jcrop_api.setSelect([0, 0, 320, 320]);//设置选择框

            $preview_pane.appendTo(jcrop_api.ui.holder);//预览必须需要
        });

        function updatePreview(c) {
            var bounds = jcrop_api.getBounds();//获取图片原始长宽
            var boundx = bounds[0];
            var boundy = bounds[1];


            //存储裁剪的图片数据，x,y,w,h

            $("#cutX").val(parseInt(c.x*imgWidth/boundx));
            $("#cutY").val(parseInt(c.y*imgWidth/boundx));
            $("#destWidth").val(parseInt(c.w*imgWidth/boundx));
            $("#destHeight").val(parseInt(c.h*imgWidth/boundx));

            if (parseInt(c.w) > 0) {
                //计算预览区域图片缩放的比例，通过计算显示区域的宽度(与高度)与剪裁的宽度(与高度)之比得到

                var xsize = $preview_container.width();
                var ysize = $preview_container.height();
                var rx = xsize / c.w;
                var ry = ysize / c.h;
                //通过比例值控制图片的样式与显示
                $preview_img.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
        }
    }

    /*保存头像*/
    function saveHeadImg(headImgUrl){
        console.log(headImgUrl);
            $.ajax({ //保存头像
            	url:basePath+'/shopE/userInfo!saveHeadImg.action',
            	type:'POST',
            	dataType:'json',
            	data:{
            		valuePath:headImgUrl
            	},
            "success": function(result) {
                var color = "red";
                if(result.flag) {
                    new $.tip({
                    "width": "200px",
                    "content": "保存成功",
                    "time": 500,
                    "color": color
                }).run();
                }else{
                	new $.tip({
                    "width": "200px",
                    "content": "保存失败",
                    "time": 500,
                    "color": color
                }).run();
                }
            }
        });
    }